﻿#include "jmysql.h"

JMySQL::JMySQL(QObject *parent) : QObject(parent)
{
    Init();
}

JMySQL::JMySQL(DataBaseInfo db)
{
    DbInfo = db;
    Init();
}

JMySQL::JMySQL(DataBaseInfo db, QString ConnectName)
{
    DbInfo = db;
    Init(ConnectName);
}

JMySQL::~JMySQL()
{
}

void JMySQL::Init(QString ConnectName)
{
    DbInfo.Server = DbInfo.Server;
    DbInfo.User = DbInfo.User;
    DbInfo.Passwd = DbInfo.Passwd;
    DbInfo.DbName = DbInfo.DbName;
    if(ConnectName.isEmpty()) {
        db = QSqlDatabase::addDatabase("QMYSQL");
    }
    else
        db = QSqlDatabase::addDatabase("QMYSQL", ConnectName);
    db.setHostName(DbInfo.Server);
    db.setPort(3306);
    db.setDatabaseName(DbInfo.DbName);
    db.setUserName(DbInfo.User);
    db.setPassword(DbInfo.Passwd);
}

bool JMySQL::ReadAreaInfo(QVector<AreaInfo> &List)
{
    List.clear();
    try {
        if(db.open()) {
            QString SQL = "SELECT id, `name`, type FROM `area` WHERE ismonitor = 1;";
            QSqlQuery query = QSqlQuery(SQL, db);
            while (query.next()) {
                AreaInfo area;
                area.AreaId = query.value("id").toInt();
                area.Type = query.value("type").toInt();
                area.AreaName = query.value("name").toString();
                List.push_back(area);
            }
            db.close();
            return true;
        }
        else {
            db.close();
            return false;
        }
    }
    catch(...) {
        db.close();
        return false;
    }
}
